package {
	import UIFree.controls.uif_popupMenu;
	import UIFree.uif_ecomponent;
	
	import api.api_okserver;
	import api.com.odnoklassniki.Odnoklassniki;
	import api.com.odnoklassniki.events.ApiCallbackEvent;
	import api.com.odnoklassniki.events.ApiServerEvent;
	
	import api_servers.api_externalserver;
	import api_servers.pi_myserver;
	import api_servers.pi_servers;
	
	import classes.ok_locale;
	import classes.ok_manager;
	
	import dialogs.pi_albums;
	import dialogs.timeAlerts.pi_alertTime;
	
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.system.Security;
	
	import manager.pi_manager;

	[SWF(width="760", height="956", backgroundColor="#FFFFFF")]
	public class pj_ok extends photo_inject {
		private var _vars: Object;
		private var _siteData: Object;
		private var _payCallBack		: Function;
		
		public function pj_ok() {
			photo_inject.APPWIDTH 		= 760;
			photo_inject.APPHEIGHT		= 956;
			pi_myserver.MODEL_NAME 		= 'pj_ok01';
			super();
			okInit();
		}
	
		override protected function initDefaults(user: Object): Object {
			var _def: Object = null;
			if (user.age < 18) { // Для детей
				if (user.sex == 0) { // Для мальчиков
					_def = {
						DEFAULT_MASK: 12381,
						DEFAULT_EFFECT: 0,
						DEFAULT_GROUP : 125
					};
				} else {	// Для девочек
					_def = {
						DEFAULT_MASK: 12381,
						DEFAULT_EFFECT: 0,
						DEFAULT_GROUP : 125
					};
				}
			} else if (user.sex == 0) { // Для мужчин
				_def = {
					DEFAULT_MASK: 12361,
					DEFAULT_EFFECT: 0,
					DEFAULT_GROUP : 125
				};
			} else {	// Для женщин
				_def = {
					DEFAULT_MASK: 12361,
					DEFAULT_EFFECT: 0,
					DEFAULT_GROUP : 125
				};
			}
			return _def;
		}
		
		override protected function securityInit(): void {
			Security.allowDomain('*');
			super.securityInit();
			if (externalserver.vars['plugins'])
				pi_servers.PLUGINS_URL = externalserver.vars['plugins'];
		}
		
		override protected function serversInit(): void {
	 		pi_servers.ADDR = ['http://188.127.228.242', 'http://188.127.228.242', 'http://oformi-foto.ru', 'http://oformi-foto.ru']			
			pi_servers.USERPHOTOHOST	= pi_servers.ADDR[1];
			pi_servers.UPLOADJPG_URL	= pi_servers.ADDR[1] + '/games/index_pj.php';
			
			pi_servers.EFFECTS_URL		= pi_servers.ADDR[3] + '/pj/plugins/filters/';
			pi_servers.MROOT_URL		= pi_servers.ADDR[3] + '/games/data/a/templates/';
			pi_servers.PREVIEW_URL		= pi_servers.ADDR[3] + '/games/data/a/templates/jpg_preview/';
			pi_servers.PLUGINS_URL		= pi_servers.ADDR[3] + '/pj/plugins/v02/mail/';
			pi_servers.IMAGESURL		= pi_servers.ADDR[3] + '/pj/images/';
			pi_servers.FLASH_URL		= getHost() + '/templates';			
		}
	
		override protected function extendList(): Object {
			return {
				'mobile'		: {
					id: 0,
					file: 'c_mobile.swf',
					icon: 'c_mobile.swf.png',
					caption: 'Как фон для сотового телефона',
					png_only: true
				},
				'SOUND'			: {
					id: 1,
					file: 'c_sound.swf',
					icon: 'c_sound.swf.png',
					caption: 'Добавить музыку к открытке'
				}, 
				'extends'		: {
					id: 2,
					file: 'c_extends.swf',
					icon: 'c_extends.swf.png',
					caption: 'Загрузить фотографию',
					load: true
				}, 
				'elems'		: {
					id: 3,
					file: 'c_elems.swf',
					icon: 'c_title.swf.png',
					caption: 'Дополнительные элементы',
					load: true
				},
				'tlt'			: {
					id: 4,
					file: 'c_title.swf'
				},
				'COR'			: {
					id: 5,
					file: 'c_correction.swf',
					load: 5 
				},
				'printer'			: {
					id: 6,
					file: 'c_printer.swf',
					load: 4
				},
				'helperMulti'			: {
					id: 7,
					file: 'c_helperMulti.swf'
				},
				'adminConsol'			: {
					id: 8,
					file: 'c_admin.swf'
				},
				'search'			: {
					id: 9,
					file: 'c_search.swf',
					load: 3
				},
				'FRAMES': {
					id		: 10,
					file	: 'c_frames.swf'
				},
				'VIN': {
					id		: 11,
					file	: 'c_vin.swf'
				}
			}
		}
			
		override protected function beforeStart(e: Event=null): void {
			_vars = flashVars;
			var a: Array 	= _vars.apiconnection.split('_');
			_vars.app_id 	= a[0];
			_vars.uid 		= _vars.logged_user_id;
			_siteData		= initSiteData();
			super.beforeStart(e);
		}

		protected function okInit(): void {
			Odnoklassniki.initialize(this, api_okserver.SECRETS[_vars.app_id]);
			Odnoklassniki.addEventListener(ApiServerEvent.CONNECTED, onConnect);
			Odnoklassniki.addEventListener(ApiServerEvent.CONNECTION_ERROR, onErrorConnection);
			Odnoklassniki.addEventListener(ApiServerEvent.PROXY_NOT_RESPONDING, onErrorConnection);
			Odnoklassniki.addEventListener(ApiServerEvent.NOT_YET_CONNECTED, onErrorConnection);
			Odnoklassniki.addEventListener(ApiCallbackEvent.CALL_BACK, doCallBack);
		}		
	
		protected function onErrorConnection(event : ApiServerEvent) : void {
			alert(app.classes.locale.MESSAGE, event.type);
		}
		
		protected function doCallBack(event: ApiCallbackEvent): void {
			if ((event.method == 'showPayment') && (event.result == 'ok')) {
				if (_payCallBack != null) _payCallBack(event);
				_payCallBack = null;
			}
		}
		
		protected function onConnect(event : ApiServerEvent) : void {
			//Odnoklassniki.setWindowSize(appSize.x, appSize.y);
			initialize();
		}
		
	
		override public function initLayers(count: int): void {
			_layers = new Array();
			for (var i: int = 0; i<count; i++)
				_layers.push(new uif_ecomponent(this, 0, 0, photo_inject.APPWIDTH, photo_inject.APPHEIGHT));
		}
		
		override public function albumAssessFromSend(albumOrPhoto: Object): Boolean {
			return true;
		}
		
		override protected function createBanners(level: int): void {
		}
		
		protected function initSiteData(): Object {
			return {								
				NOUSERALBUMACCESS	: 'Нет доступа к альбомам пользователя, приложение не установлено.\nПригласите друга для получения доступа к альбомам.',
				NOACCESSPHOTOS		: 'Нет доступа к вашим фотографиям!\nВы хотите открыть доступ к фотографиям для приложения?',
				INVITEDESC			: 'Приглашение в приложение "Прикольное перевоплощение"',
				EMPTYRESULT			: 'Пустой результат'
			};
		}
		
		override public function getClasses(): Object {
			var lc: Object = super.getClasses();
			lc.alertTime 	= pi_alertTime;
			lc.popupMenu 	= uif_popupMenu;
			lc.locale		= ok_locale;
			return lc;
		}
		
		public function get flashVars(): Object {
 			return Object( LoaderInfo(stage.loaderInfo ).parameters );			
		}
		
		override protected function createManager():pi_manager {
			return new ok_manager(this);
		}
	
		override protected function createExternalServer(): api_externalserver {
			return new api_okserver(this, _vars);
		}
		
		public function showInviteDialog(): void {
			Odnoklassniki.showInvite(sitedata.INVITEDESC);
		}
		
		public function checkErrorData(a_data: Object): Boolean {
			function errorEvent(): void {
				switch (a_data.error_code) {
					case 10: alert(app.classes.locale.ERROR, sitedata.NOUSERALBUMACCESS, showInviteDialog);
							break;
					default: alert(app.classes.locale.ERROR, a_data.error_msg);
				}
			}
		
			
			if (!a_data) {
				alert(app.classes.locale.ERROR, sitedata.EMPTYRESULT);
				return true;
			} else if (a_data.hasOwnProperty('error_code')) {
				errorEvent();
				return true;
			}
			return false;
		}
		
		public function get sitedata(): Object {
			return _siteData;
		}
		
		override protected function albumsPrepare(uid: String, a_albums: Array): Array {
			var result: Array = new Array();
			function checkAccess(album: Object): Boolean {
				return true;
			}
			for each (var album: Object in a_albums) {
				if (checkAccess(album)) {
					album.smallTitle = Utils.ll(album.title?album.title:album.created, 16);		
					result.push(album);
				}
			}
			return result;
		}
		
		override protected function afterLoadAlbums(uid: String, a_albums: Array): void {
			var list: Array = albumsPrepare(uid, a_albums);
			
			if (!_albums) _albums = new pi_albums(_layers[0], list, 0, 780, APPWIDTH, 100, 'tabBox');
			else _albums.assignAlbums(uid, list);

		}
	}
}
